package test;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;

class ImageToBase64
{
    public static void main(String[] args)
    {
        String imageUrl = "https://d18sdvl5kwtzlk.cloudfront.net/avatar/18.png";

        try {
            // 创建 URL 对象并打开连接
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();

            // 读取图片内容并转换为 Base64
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            String base64 = Base64.getEncoder().encodeToString(imageBytes);

            // 输出结果
            System.out.println(base64);

            // 关闭连接和流
            inputStream.close();
            byteArrayOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
